let _ = require('lodash');
let config = require('../config');
let sequelize = require('../libs/db.lib');
let videoModel = require('../models/video.model');
let classModel = require('../models/class.model');
let userModel = require('../models/user.model');
let jwt = require('jsonwebtoken');
let Op = require('sequelize').Op;
const url = require('url');

function currentUid(req) {
    let token = req.body.token;
    let decoded = jwt.decode(token, config.tokenSecret);
    return decoded.id;
}

function fixPic(pic) {
    try {
        const urlInfo = url.parse(pic);
        if (config.system.pic2tu.pic && config.system.pic2tu.hosts && config.system.pic2tu.hosts.includes(urlInfo.host)) {
            pic = config.system.pic2tu.pic + pic;
        }
    } catch (e) {
        console.log(e);
    }
    return pic;
}

module.exports = {
    /**
     * 获取所有视频
     * @param req
     * @param res
     * @param next
     */
    videos(req, res, next) {
        let cid = req.body.cid;
        let page = req.body.page;
        let pageSize = req.body.pageSize;
        let picFix = req.body.picFix;
        if (_.isNil(cid)) {
            cid = 1;
        }
        if (_.isNil(page)) {
            page = 1;
        }
        if (_.isNil(pageSize)) {
            pageSize = 20;
        }
        if (_.isNil(picFix)) {
            picFix = false;
        }
        classModel.findOne({attributes: ['leaf', 'visible'], where: {id: cid}}).then(c => {
            if (!c) {
                res.jsonFail('分类不存在!');
                return;
            }
            if (!c.visible) {
                res.jsonFail('分类不可见!');
                return;
            }
            let cids = c.leaf;
            cids.unshift(cid);
            return videoModel.findAndCountAll({
                attributes: ['id', 'name', 'pic'],
                where: {
                    cid: {
                        [Op.in]: cids,
                    },
                },
                order: [
                    ['last', 'DESC'],
                ],
                limit: pageSize,
                offset: pageSize * (page - 1),
            }).then(vs => {
                if (picFix) {
                    for (let vod of vs.rows) {
                        vod.pic = fixPic(vod.pic);
                    }
                }
                res.jsonSuccess(vs);
            }).catch(e => {
                res.jsonFail(e.message);
            });
        }).catch(e => {
            res.jsonFail(e.message);
        });
    },

    /**
     * 搜索视频
     * @param req
     * @param res
     * @param next
     */
    search(req, res, next) {
        let keyword = req.body.key;
        let page = req.body.page;
        let pageSize = req.body.pageSize;
        let picFix = req.body.picFix;
        if (_.isNil(keyword) || _.toString(keyword).trim().length === 0) {
            res.jsonFail('关键词不能为空!');
            return;
        }
        if (_.isNil(page)) {
            page = 1;
        }
        if (_.isNil(pageSize)) {
            pageSize = 20;
        }
        if (_.isNil(picFix)) {
            picFix = false;
        }
        videoModel.findAndCountAll({
            attributes: ['id', 'name', 'pic'],
            where: sequelize.literal(`MATCH (tags) AGAINST('${keyword}')`),
            order: [
                ['last', 'DESC'],
            ],
            limit: pageSize,
            offset: pageSize * (page - 1),
        }).then(vs => {
            if (picFix) {
                for (let vod of vs.rows) {
                    vod.pic = fixPic(vod.pic);
                }
            }
            res.jsonSuccess(vs);
        }).catch(e => {
            res.jsonFail(e.message);
        });
    },

    /**
     * 获取单个视频
     * @param req
     * @param res
     * @param next
     */
    detail(req, res, next) {
        let id = req.body.id;
        let picFix = req.body.picFix;
        if (_.isNil(id)) {
            res.jsonFail('视频不存在!');
            return;
        }
        if (_.isNil(picFix)) {
            picFix = false;
        }
        id = _.toInteger(id);
        videoModel.findOne({where: {id: id}}).then(v => {
            if (!v) {
                res.jsonFail('视频不存在!');
                return;
            }
            if (picFix) {
                v.pic = fixPic(v.pic);
            }

            let playlist = v.playlist;
            for (let key in playlist) {
                for (let index in playlist[key]) {
                    delete playlist[key][index].url;
                }
            }
            v.playlist = playlist;

            // 查历史记录
            let uid = currentUid(req);
            return userModel.findOne({attributes: ['history'], where: {id: uid}}).then(u => {
                let found = false;
                if (u && u.history) {
                    for (let idx in u.history) {
                        if (u.history[idx].id === id) {
                            v.setDataValue('history', u.history[idx]);
                            found = true;
                            break;
                        }
                    }
                } else {
                    found = false;
                }
                if (!found) {
                    v.setDataValue('history', {
                        src: _.findKey(v.playlist),
                        index: 0,
                    });
                }
                res.jsonSuccess(v);
            }).catch(e => {
                v.setDataValue('history', {
                    src: _.findKey(v.playlist),
                    index: 0,
                });
                res.jsonSuccess(v);
            });
        }).catch(e => {
            res.jsonFail(e.message);
        });
    },

    /**
     * 获取播放信息
     * @param req
     * @param res
     * @param next
     */
    play(req, res, next) {
        let id = req.body.id;
        let src = req.body.src;
        let index = req.body.index;
        if (_.isNil(id) || _.isNil(src) || _.isNil(index)) {
            res.jsonFail('播放参数错误!');
            return;
        }
        src = src.trim();
        videoModel.findOne({attributes: ['playlist'], where: {id: id}}).then(v => {
            if (!v) {
                res.jsonFail('视频不存在!');
                return;
            }
            if (!v.playlist.hasOwnProperty(src)) {
                res.jsonFail(`视频源${src}不存在!`);
                return;
            }
            if (index < 0 || index >= v.playlist[src].length) {
                res.jsonFail(`视频源${src}的索引${index}不存在!`);
                return;
            }
            let url = v.playlist[src][index].url;
            let linkPre = '';
            if (config.system.srcPlayers && config.system.srcPlayers.hasOwnProperty(src)) {
                linkPre = config.system.srcPlayers[src];
            } else if (config.system.vipFlags && config.system.vipFlags.indexOf(src) >= 0) {
                linkPre = config.system.vipParser;
            }
            url = linkPre + url;
            // 记历史记录
            let uid = currentUid(req);
            return userModel.findOne({attributes: ['id', 'history'], where: {id: uid}}).then(async u => {
                if (u) {
                    let history = u.history ? u.history : [];
                    for (let idx in history) {
                        if (history[idx].id === _.toInteger(id)) {
                            history.splice(idx, 1);
                            break;
                        }
                    }
                    const maxRecord = 30;
                    if (history.length > maxRecord) {
                        history.splice(maxRecord, history.length - maxRecord + 1);
                    }
                    history.unshift({id: _.toInteger(id), src: src, index: _.toInteger(index)});
                    u.history = history;
                    await u.save();
                }
                res.jsonSuccess({url: url});
            }).catch(e => {
                res.jsonSuccess({url: url});
            });
        }).catch(e => {
            res.jsonFail(e.message);
        });
    },
};
